var G_windowTitle;
var form;
var G_id;
var zTree;
var G_pId = null;
var checkedTrRoleid;
var checkedTrOrgid;
$(document).ready(function () {
  initLayui();
  initTable();
  initMenuTree();
  setTimeout(() => {
    getSubMenu();
  }, 100);
});

function initLayui() {
  layui.use(['form'], function () {
    form = layui.form;

    form.on('submit(filter)', function (data) {
      initTable();
      return false;
    });

    form.on('submit(save)', function (data) {
      var params = {
        id: G_windowTitle == '新增' ? null : G_id,
        name: data.field.name,
        description: data.field.description,
      };
      save(params);
      return false;
    });

    form.on('submit(saveRole)', function (data) {
      if (checkedTrRoleid) {
        var checkedNodes = getCheckedNodes();
        var menuRoleList = [];
        $.each(checkedNodes, function (i, val) {
          menuRoleList.push(val.id);
        });
        var data = {
          roleId: checkedTrRoleid,
          orgId: checkedTrOrgid,
          menuRoleList: menuRoleList,
        };
        AjaxRequest('/menu/role/save', callBack, data, 'post');

        function callBack(result) {
          if (result.status == 200) {
            layer.msg('保存成功!');
          }
        }
        return false;
      } else {
        layer.msg('请先选中左侧表格行！');
      }
    });
  });
}

// 新增编辑弹窗
function showWindow(title, res) {
  layer.open({
    type: 1,
    title: title,
    skin: 'default-class',
    area: ['4.5rem', 'auto'],
    // shade: false,
    move: false,
    closeBtn: 2,
    id: 1, //设置该值后，不管是什么类型的层，都只允许同时弹出一个。
    content: `<form class="layui-form" lay-filter="saveForm" style="margin: .3rem;">
                <div class="layui-form-item">
                  <label class="layui-form-label">角色名称</label>
                  <div class="layui-input-block">
                    <input type="text" name="name" autocomplete="off" class="layui-input" lay-verify="required">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">角色描述</label>
                  <div class="layui-input-block">
                    <input type="text" name="description" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item form-btn" style="text-align:center">
                  <div class="layui-input-block" style="margin-left: 0;">
                    <button class="layui-btn" lay-submit lay-filter="save">保存</button>
                  </div>
                </div>
              </form>`, //这里content是一个普通的String
    success: function (layero, index) {
      G_windowTitle = title;
      form.render();
      if (title == '编辑') {
        G_id = res.id;
        //给表单赋值
        form.val('saveForm', {
          name: res.name,
          description: res.description,
        });
      }
    },
  });
}

// 保存表单
function save(data) {
  AjaxRequest('/role/save', callBack, data, 'post');

  function callBack(result) {
    if (result.status == 200) {
      layer.msg('保存成功！');
      initTable();
      layer.closeAll();
    } else {
      layer.msg('保存失败！');
    }
  }
}

function initTable() {
  layui.use('table', function () {
    var table = layui.table;
    var height = $('.search-content').innerHeight() - 20;

    //第一个实例
    table.render({
      title: '',
      height: height,
      text: {
        none: '暂无数据',
      },
      elem: '#table',
      skin: 'nob',
      headers: {
        SessionId: JSON.parse(localStorage.getItem('userInfo')).sessionId,
      },
      url: ajaxPrefix() + '/role/list',
      where: {},
      parseData: function (res) {
        //res 即为原始返回的数据
        return {
          code: res.status == 200 ? 0 : 1, //解析接口状态
          msg: res.message, //解析提示文本
          count: res.result?res.result.total:0, //解析数据长度
          data: res.result?res.result.data:[], //解析数据列表
        };
      },
      request: {
        pageName: 'pageNum', //页码的参数名称，默认：page
        limitName: 'pageSize', //每页数据量的参数名，默认：limit
      },
      page: {
        //开启分页
        limit: 10,
      },
      cols: [
        [
          //表头
          {
            field: 'name',
            title: '角色名称',
            align: 'center',
          },
          {
            field: 'description',
            title: '角色描述',
            align: 'center',
          },
          {
            field: 'operation',
            title: '操作',
            align: 'center',
            width: 200,
            toolbar: $('#toolbar'),
            // templet: function (d) {
            //   let res = JSON.stringify(d);
            //   return `<div class="table-tool">
            //             <div onclick='showWindow("编辑",${res})'>
            //               <img src="../static/img/edit.png">编辑
            //             </div>
            //             <div onclick='showDelWindow(${res})'>
            //               <img src="../static/img/delete.png">删除
            //             </div>
            //           </div>`
            // },
          },
        ],
      ],
    });

    //触发行单击事件
    table.on('row(filter)', function (obj) {
      // console.log(obj) //得到当前行元素对象
      // console.log(obj.data) //得到当前行数据
      obj.tr.addClass('tr-active').siblings().removeClass('tr-active');
      checkedTrRoleid = obj.data.id;
      checkedTrOrgid = obj.data.orgId;
      AjaxRequest('/menu/role?roleId=' + obj.data.id, callBack);

      function callBack(result) {
        if (result.status == 200) {
          var data = result.result;
          selectNode(data);
        }
      }
    });

    //触发单元格工具事件
    table.on('tool(filter)', function (obj) {
      var data = obj.data;
      //console.log(obj)
      if (obj.event === 'del') {
        showDelWindow(data);
      } else if (obj.event === 'edit') {
        showWindow('编辑', data);
      }
    });
  });
}

// 选中树节点
function selectNode(data) {
  zTree.cancelSelectedNode(); // 取消选中的所有节点
  zTree.checkAllNodes(false); // 取消勾选的所有节点
  if (data.length > 0) {
    $.each(data, function (i, val) {
      var node = zTree.getNodeByParam('id', val.id);
      if (node != null) {
        zTree.checkNode(node, true, false);
        //获取该节点父节点
        var parent = node.getParentNode();
        if (parent) {
          if (!parent.open) {
            //如果父节点没有展开则展开父节点
            zTree.expandNode(parent, true, true, false);
          }
        }
      }
    });
  }
}

function initMenuTree() {
  AjaxRequest('/menu/tree', callBack);

  function callBack(result) {
    var zNodes = result.result;
    $.each(zNodes, function (i, val) {
      val.icon = '';
    });
    var setting = {
      check: {
        enable: true,
      },
      data: {
        simpleData: {
          enable: true,
        },
      },
    };
    zTree = $.fn.zTree.init($('#menu-tree'), setting, zNodes);
  }
}

// 获取选中节点
function getCheckedNodes() {
  var zTree = $.fn.zTree.getZTreeObj('menu-tree');
  return zTree.getCheckedNodes(true);
}

function showDelWindow(res) {
  layer.confirm(
    '确认是否删除?',
    {
      btn: ['确认', '取消'], //按钮
    },
    function () {
      AjaxRequest('/role/delete?id=' + res.id, callBack);

      function callBack(result) {
        if (result.status == 200) {
          layer.msg('删除成功!');
          initTable();
          initMenuTree();
          layer.closeAll();
        }
      }
    }
  );
}
